package com.yixin.hospital.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.bo.PageInfo;
import com.yixin.hospital.entity.domain.DrugDepositoryDrug;
import com.yixin.hospital.entity.domain.GodownCancelDrug;
import com.yixin.hospital.entity.domain.GodownExchangeDrug;
import com.yixin.hospital.entity.dto.req.purchaseorder.GoDownCancelDrugReqDTO;
import com.yixin.hospital.entity.dto.req.purchaseorder.GoDownExchangeDrugReqDTO;
import com.yixin.hospital.entity.dto.req.purchaseorder.GoDownExchangeDrugStatusReqDTO;
import com.yixin.hospital.entity.vo.DrugDepositoryVo;
import com.yixin.hospital.entity.vo.GoDownCancelDrugVo;
import com.yixin.hospital.entity.vo.GoDownExchangeDrugVo;
import com.yixin.hospital.enums.DrugDepositoryOtpTypeEnum;
import com.yixin.hospital.enums.GoDownCancelStatusEnum;
import com.yixin.hospital.enums.GoDownExchangeStatusEnum;
import com.yixin.hospital.mapper.extend.GodownCancelDrugExtendMapper;
import com.yixin.hospital.service.*;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.yixin.hospital.common.Constant.format;

@RestController
@RequestMapping("/input-godown-cancel")
@Api(value = "调库单管理", tags = "调库单管理")
public class InputGodownCancelController {

    @Resource
    GodownDrugService godownDrugService;
    @Resource
    DrugDepositoryDrugService drugDepositoryDrugService;
    @Resource
    DrugDepositoryController drugDepositoryController;
    @Resource
    GodownCancelDrugExtendMapper godownCancelDrugExtendMapper;
    @Resource
    GodownCancelDrugService godownCancelDrugService;

    @GetMapping("/list2")
    @ApiOperation(value = "返库单列表")
    public ApiResult<?> list(HttpServletRequest request, @RequestParam int currentPage, @RequestParam int pageSize) {
        ApiResult<List<DrugDepositoryVo>> outputListApiResult = drugDepositoryController.availableList(request, DrugDepositoryOtpTypeEnum.OUTPUT.getCode());
        if (CollectionUtils.isEmpty(outputListApiResult.getData())) return ApiResult.success(outputListApiResult);

        List<Long> drugDepositoryIds = outputListApiResult.getData().stream().map(DrugDepositoryVo::getId).collect(Collectors.toList());
        IPage<GoDownCancelDrugVo> page = godownCancelDrugExtendMapper.pageVo(Page.of(currentPage, pageSize), drugDepositoryIds);
        PageInfo<GoDownCancelDrugVo> pageInfo = new PageInfo<>();
        BeanUtil.copyProperties(page, pageInfo);
        pageInfo.setRecords(BeanUtil.copyToList(page.getRecords(), GoDownCancelDrugVo.class));
        return ApiResult.success(pageInfo);
    }

    @GetMapping("/listInfo")
    @ApiOperation(value = "返库单详情")
    public ApiResult<?> ListInfo(@RequestParam String code) {
        List<GoDownCancelDrugVo> detailList = godownCancelDrugExtendMapper.detail(code);
        return ApiResult.success(detailList);
    }

    @PostMapping("/godown-cancel-drug")
    @ApiOperation(value = "申请返库")
    @Transactional
    public ApiResult<?> goDownCancelDrug(@Valid @RequestBody GoDownCancelDrugReqDTO goDownDrugReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        List<GodownCancelDrug> godownDrugList = new ArrayList<>();
        String code = "FK" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
        for (GoDownCancelDrugReqDTO.GoDownDrugBO goDownDrugBO : goDownDrugReqDTO.getGoDownDrugBOList()) {
            GodownCancelDrug godownDrug = new GodownCancelDrug();
            godownDrug.setCode(code);
            godownDrug.setDrugDepositoryDrugId(goDownDrugBO.getDrugDepositoryDrugId());
            godownDrug.setSourceNum(goDownDrugBO.getSourceNum());
            godownDrug.setPutNum(goDownDrugBO.getNum());
            godownDrug.setCreatedBy(userName);
            godownDrug.setUpdatedBy(userName);
            godownDrugList.add(godownDrug);
        }
        godownCancelDrugService.saveBatch(godownDrugList);
        return ApiResult.success();
    }

    @PostMapping("/godown-cancel-drug-status")
    @ApiOperation(value = "返库")
    @Transactional
    public ApiResult<?> goDownCancelDrugStatus(@Valid @RequestBody GoDownExchangeDrugStatusReqDTO goDownExchangeDrugStatusReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        List<GodownCancelDrug> godownCancelDrugList = godownCancelDrugService.list(new LambdaQueryWrapper<GodownCancelDrug>().eq(GodownCancelDrug::getCode, goDownExchangeDrugStatusReqDTO.getCode()));
        GodownCancelDrug queryGodownCancelDrug = godownCancelDrugList.get(0);
        if (queryGodownCancelDrug.getStatus().equals(GoDownCancelStatusEnum.DOWN.getCode())) return ApiResult.error();
        List<Long> outputIds = godownCancelDrugList.stream().map(GodownCancelDrug::getDrugDepositoryDrugId).collect(Collectors.toList());
        Map<Long, DrugDepositoryDrug> drugDepositoryDrugMap = drugDepositoryDrugService.listByIds(outputIds).stream().collect(Collectors.toMap(DrugDepositoryDrug::getId, Function.identity()));
        List<DrugDepositoryDrug> drugDepositoryDrugList = new ArrayList<>();
        for (GodownCancelDrug godownCancelDrug : godownCancelDrugList) {
            // 减库存/加库存
            DrugDepositoryDrug drugDepositoryDrug;
            drugDepositoryDrug = drugDepositoryDrugMap.get(godownCancelDrug.getDrugDepositoryDrugId());
            drugDepositoryDrug.setNum(drugDepositoryDrug.getNum() - godownCancelDrug.getPutNum());
            // 改状态
            godownCancelDrug.setStatus(GoDownCancelStatusEnum.DOWN.getCode());
            godownCancelDrug.setUpdatedBy(userName);
            godownCancelDrug.setUpdatedTime(new Date());
            drugDepositoryDrug.setUpdatedBy(userName);
            drugDepositoryDrug.setUpdatedTime(new Date());
            drugDepositoryDrugList.add(drugDepositoryDrug);
        }
        godownCancelDrugService.updateBatchById(godownCancelDrugList);
        drugDepositoryDrugService.updateBatchById(drugDepositoryDrugList);
        return ApiResult.success();
    }

}
